/*
 * @Description:
 * @Author: huxianc
 * @Date: 2020-11-12 13:44:21
 * @LastEditors: huxianc
 * @LastEditTime: 2020-11-17 11:02:04
 */
import { stageWH } from "./stage_config";

/**
 * @description: 判断是否在屏幕内,在则返回传入的数值，不然的话修正数值返回
 * @param {number} x
 * @param {number} y
 * @param {number} scale 缩放
 * @return {object} {x,y}
 */
export const isInScreen = (x, y, scale) => {
  const position = {
    x: x,
    y: y
  };
  // 判断图片 x 轴超出右边界
  if (window.innerWidth - x >= stageWH.width * scale) {
    // console.log("右");
    position.x = window.innerWidth - stageWH.width * scale;
  }
  // 判断图片 x 轴超出左边界
  if (x >= 0) {
    position.x = 0;
  }
  // 判断图片 y 轴上边界
  if (y >= 0) {
    position.y = 0;
  }
  // 判断图片 y 轴下边界
  if (window.innerHeight - y >= stageWH.height * scale) {
    position.y = window.innerHeight - stageWH.height * scale;
  }
  return position;
};

/**
 * @description: 加载图片完成后才执行回调
 * @param {object} sources 图片资源对象
 * @param {function} callback 回调函数 的参数就是source，值是img对象
 * @return {void} undefined
 */

export const loadImages = (sources, callback) => {
  // 存放需要加载图片的位置
  // const publicDir = "/imgs/";
  const publicDir = "";
  const images = {};
  let loadedImages = 0;
  let numImages = 0;
  // eslint-disable-next-line no-unused-vars
  for (let src in sources) {
    // 获取对象中总共有多少张图片
    numImages++;
  }
  for (let src in sources) {
    images[src] = new Image();
    images[src].onload = () => {
      if (++loadedImages >= numImages) {
        callback(images);
      }
    };
    images[src].src = publicDir + sources[src];
  }
};
